package superminer.xinfang.com.ipreport.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import superminer.xinfang.com.ipreport.R;
import superminer.xinfang.com.ipreport.base.BaseApplication;
import superminer.xinfang.com.ipreport.bean.LoginBean;
import superminer.xinfang.com.ipreport.bean.VersionBean;
import superminer.xinfang.com.ipreport.network.HttpUtils;
import superminer.xinfang.com.ipreport.network.NetHelper;
import superminer.xinfang.com.ipreport.network.TcpNetHelper;
import superminer.xinfang.com.ipreport.util.MyGson;
import superminer.xinfang.com.ipreport.util.NetWorkUtil;
import superminer.xinfang.com.ipreport.util.SPUtil;
import superminer.xinfang.com.ipreport.util.ToastUtil;
import superminer.xinfang.com.ipreport.util.UpdateManager;
import superminer.xinfang.com.ipreport.util.netty.INettyClient;
import superminer.xinfang.com.ipreport.util.netty.NettyClient;
import superminer.xinfang.com.ipreport.view.dialog.LoadingDialog;
import superminer.xinfang.com.ipreport.view.dialog.UpdateDialog;

/**
 * 登录
 */
public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.edit_phone)
    EditText edit_phone;//账户名

    @BindView(R.id.edit_password)
    EditText edit_password;//密码

    private INettyClient.OnDataReceiveListener onDataReceiveListener;
    private LoadingDialog loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        loadingDialog = new LoadingDialog(this, 0);
        SPUtil spUtil = new SPUtil(this, BaseApplication.FILENAME);
        edit_phone.setText("" + spUtil.getString(BaseApplication.TEL, ""));
        edit_password.setText("" + spUtil.getString(BaseApplication.PASSWORD, ""));

        setSetDataReceiveListener();
        NettyClient.getInstance().connect(BaseApplication.IPADRESS, BaseApplication.PORT);

        //版本更新
        getVersionInfo();
    }

    private void getVersionInfo() {
        NetHelper.GetVersionInfo(new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {

                VersionBean baseBean = MyGson.getInstance().fromJson(data, VersionBean.class);
                if (baseBean.getType()==1)
                {

                    int verCode = getVerCode(LoginActivity.this);
                    if (verCode<Integer.valueOf(baseBean.getData().getVersionCode()))
                    {
                        //跟新
                        //这里来检测版本是否需要更新
                        UpdateDialog updateDialog = new UpdateDialog(LoginActivity.this, R.style.dialog, baseBean.getData().getUpdateInfo(), baseBean.getData().getUpdateUrl());
                        updateDialog.show();
                    }else
                    {
//                        ToastUtil.showToast(LoginActivity.this,"当前是最新版本，不需要更新");
                    }
                }

            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                ToastUtil.showToast(getApplicationContext(), msg);
            }
        });

    }

    /**
     * 获取软件版本号
     * @param context
     * @return
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            //注意："com.example.try_downloadfile_progress"对应AndroidManifest.xml里的package="……"部分
            verCode = context.getPackageManager().getPackageInfo(
                    "superminer.xinfang.com.ipreport", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {

        }
        return verCode;
    }
    /**
     * 设置数据监听
     */
    private void setSetDataReceiveListener() {
        onDataReceiveListener = new INettyClient.OnDataReceiveListener() {
            @Override
            public void onDataReceive(int mt, String jsons) {

                Log.i("-->", "LoginActivity返回数据：" + mt +" json:"+ jsons);
                loadingDialog.dismiss();
//                handler.sendEmptyMessage(mt);
                //登录成功返回
                if (mt==TcpNetHelper.ReLogin)
                {

                    LoginBean loginBean = MyGson.getInstance().fromJson(jsons, LoginBean.class);
                    if (loginBean.isIsSuccess())
                    {
                        startActivity(new Intent(LoginActivity.this,Main2Activity.class));
                        SPUtil spUtil = new SPUtil(LoginActivity.this, BaseApplication.FILENAME);
                        spUtil.putString(BaseApplication.TEL,edit_phone.getText().toString().trim());
                        spUtil.putString(BaseApplication.PASSWORD,edit_password.getText().toString().trim());
                        finish();
                    }else
                    {
                        ToastUtil.showToast(LoginActivity.this,loginBean.getMessage());
                    }

                }



            }
        };
        if (onDataReceiveListener!=null)
            NettyClient.getInstance().addDataReceiveListener(onDataReceiveListener);
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        NettyClient.getInstance().delectDataReceiveListener(onDataReceiveListener);
    }

    @OnClick({R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login://登录
                if(check())
                {
                    loadingDialog.show();
                    TcpNetHelper.login(edit_phone.getText().toString().trim(),edit_password.getText().toString().trim());
                }
                break;


        }
    }

    private boolean check() {
        if ("".equals(edit_phone.getText().toString().trim()))
        {
            ToastUtil.showToast(this,"账号不能为空");
            return false;
        }
        if ("".equals(edit_password.getText().toString().trim()))
        {
            ToastUtil.showToast(this,"密码不能为空");
            return false;
        }
        if (!NetWorkUtil.checkNet(getApplicationContext())) {
            ToastUtil.showToast(getApplicationContext(), getString(R.string.error_net));
            return false;
        }
        return true;
    }

}
